"""
# @file uavOnline.py
# @author Makaka
# @date 2023-12-12
# @brief 通过post方法将无人机信息上传到服务器
"""
from myfunction import *

logger = setup_logger('online.log')
ONLINEURL = get_config_value('config.yaml', 'ONLINEURL', logger=logger)
CONNECT_MAX_RETRIES = 1000 # 请求上线网址最大尝试数目
DELAY = 5

uav_data = {
    "uavId": "", 
    "uavMac": "",  # 待更新
    "uavTimestamp": 0,  # 待更新
    "uavName": "M300_1", 
    "uavType": "MATRICE 300",
    "uavManufacturer": "dji",
    "uavColor": "red",
    "uavSize": "810*670*430mm", 
    "uavBatteryCapacity": "5935mAh",
    "uavIp": "", # 待更新
    "uavWingType":"2",
    "payload": ""
}  

def get_mac_address():
    mac = uuid.getnode()
    return ':'.join(('%012X' % mac)[i:i+2] for i in range(0, 12, 2))

def get_timestamp():
    timestamp_seconds = time.time()
    # 将时间戳转换为毫秒级别的13位时间戳
    timestamp_milliseconds = int(timestamp_seconds * 1000)
    return timestamp_milliseconds

def get_first_ip():
    ##############################
    # @description 获取无人机ip  hostname -I
    # @return ip_addresses[0] 
    ##############################n
    try:
        # 执行命令并捕获输出
        result = subprocess.run(['hostname', '-I'], capture_output=True, text=True, check=True)
        
        # 获取命令输出并以空格为分隔符拆分IP地址
        ip_addresses = result.stdout.strip().split()

        # 返回第一个IP地址
        if ip_addresses:
            return ip_addresses[0]
        else:
            return None
    except subprocess.CalledProcessError as e:
        logger.info(f"Error: {e}")
        return None

if __name__ == "__main__":
    uav_data["uavMac"] = get_mac_address()
    uav_data["uavTimestamp"] = get_timestamp()
    uav_data["uavIp"] = get_first_ip()
    uav_data["uavId"] = get_config_value('config.yaml', 'uavId', logger=logger)
    uav_data["uavName"] = get_config_value('config.yaml', 'uavName', logger=logger)
    uav_data["uavType"] = get_config_value('config.yaml', 'uavType', logger=logger)
    uav_data["uavManufacturer"] = get_config_value('config.yaml', 'uavManufacturer', logger=logger)
    uav_data["uavColor"] = get_config_value('config.yaml', 'uavColor', logger=logger)
    uav_data["uavSize"] = get_config_value('config.yaml', 'uavSize', logger=logger)
    uav_data["uavBatteryCapacity"] = get_config_value('config.yaml', 'uavBatteryCapacity', logger=logger)
    uav_data["uavWingType"] = get_config_value('config.yaml', 'uavWingType', logger=logger)
    uav_data["payload"] = get_config_value('config.yaml', 'payload', logger=logger)

    uav_json = json.dumps(uav_data)

    logger.info("无人机上线数据" + str(uav_json))
    for attempt in range(CONNECT_MAX_RETRIES):
        try:
            response = requests.post(ONLINEURL, data=uav_json, headers={'Content-Type': 'application/json'})
            if response.status_code == 200:
                logger.info(response.text)
                # 请求成功，跳出循环
                break
        except requests.exceptions.RequestException as e:
            # 请求失败，打印错误信息
            logger.info(e)
        
        # 等待一段时间再次尝试
        time.sleep(DELAY)
